package com.itcast.netty.codec.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.Map;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-22 22:08
 **/
public class ServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                FullHttpRequest fullHttpRequest) throws Exception {
        //解析FullHttpRequest,得到请求参数
        Map<String, String> paramMap = new RequestParser(fullHttpRequest).parse();
        String name = paramMap.get("name");
        
        //构造响应体
        StringBuilder sb = new StringBuilder();
        sb.append("<h1>");
        sb.append("你好, ").append(name);
        sb.append("</h1>");
        
        //构造响应对象
        FullHttpResponse httpResponse =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        //设置响应头
        httpResponse.headers()
                .set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
        
        //设置响应体
        httpResponse.content().writeBytes(Unpooled.copiedBuffer(sb, CharsetUtil.UTF_8));
        
        //发送给终端
        channelHandlerContext.writeAndFlush(httpResponse)
                //操作完成后,将channel关闭
                .addListener(ChannelFutureListener.CLOSE);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) throws Exception {
        
        cause.printStackTrace();
        ctx.close();
    }
}
